import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';
import { validateConfig } from '@angular/router/src/config';
@Pipe({
  name: 'findListingFilter'
})
export class FindListingFilter implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) {
        sessionStorage.removeItem('searchText');
        return items;
    }
    searchText =  _.lowerCase(searchText);
    sessionStorage.setItem('searchText', searchText);
    return _.filter(items, (item)=>{

        // filter by price range  
        if (item.priceRange) {
          const found = item.priceRange.replace(/\,/g, '').match(/\d+/g); //Zhan: Remove the commar and extract the number from  price range
          const lowestPrice = found[0];
          const highestPrice = found[1];
          if (Number(searchText) >= Number(lowestPrice) && Number(searchText) <= Number(highestPrice)) {
            return true;
          }
        }

        // filter by feature name
        if (item.iFeatures.length > 0) {
          const hasFeature = item.iFeatures.find(feature => {
            return _.includes(_.lowerCase(feature.name), searchText);
          });
          if (hasFeature) {
            return true;
          }
        }
      return _.includes(_.lowerCase(item.name),searchText) ||
             _.includes(_.lowerCase(item.buildingAddress),searchText) ||
             (item.feature && _.includes(_.lowerCase(item.feature.name),searchText)) ||
             _.includes(_.lowerCase(item.state),searchText) ||
             _.includes(_.lowerCase(item.suburb),searchText) ||
             _.includes(_.lowerCase(item.city),searchText) ||
             _.includes(_.lowerCase(item.country),searchText) ||
             //_.includes(_.lowerCase(item.priceRange),searchText) || //Zhan: No need to do price range search here as it has been processed in the previous line
             _.includes(_.lowerCase(item.type),searchText);

    });

  }
}
